<template>
  <div class="log-content" v-loading="uploadLoading" ref='uploadView' :class="{
    'form flex': showFormType !== 'table',
    'upload-table-view': showFormType === 'table',
  }">
    <template v-if="showFormType === 'table'">
      <!-- 标题部分 -->
      <!-- <template v-if="field.options.title || config.title">
        <div class="upload-table-view-title">
          <div class="upload-table-view-title-icon">
            <el-icon name="collection-tag" />
          </div>
          <div class="upload-table-view-title-text">
            {{ field.options.title || config.title }}
          </div>
        </div>
      </template> -->
      <!-- 表格部分 -->
      <div class="upload-table-view-table">
        <!-- 按钮部分 -->
        <div class="upload-table-view-btns">
          <div class="upload-table-view-btns-group flex">
            <el-space>
              <!-- 操作按钮插槽 -->
              <slot name="uploadBtn" v-if="$slots.uploadBtn"></slot>
              <template v-if="hasPermission('isUpload') && !$slots.uploadBtn">
                <el-upload :multiple="field.options.multipleSelect" 
                  :action="field.options.uploadApi || ''" :http-request="uploadFile" :show-file-list="false"
                  :on-success="uploadSuccess" :before-upload="fileBeforeUpload">
                  <el-button type="primary"><el-icon class="el-icon--left">
                      <Upload />
                    </el-icon>上传
                  </el-button>
                </el-upload>
              </template>

              <template v-if="hasPermission('isDownload')">
                <el-button type="primary" @click="toDownloads()" :disabled="!isDownload_talble">
                  <el-icon class="el-icon--left">
                    <Download />
                  </el-icon>批量下载
                </el-button>
              </template>

              <template v-if="hasPermission('isDeleted')">
                <el-button type="primary" @click="allDelete" :disabled="!isDownload_talble">
                  <el-icon class="el-icon--left">
                    <Delete />
                  </el-icon>批量删除
                </el-button>
              </template>
            </el-space>
            
          </div>
        </div>
        <el-table :data="flowFileList" style="width: 100%; height: 90%" :border="true" max-height="630" :hasNO="false" :hasC="true"
          @selection-change="selectedChange" size="small" row-key="id" ref="flowFileListRef" :key="randomKey">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="originalFilename" label="文件名称" min-width="240">
            <template v-slot="scope">
              <el-input v-if="scope.row.showInput" v-model="scope.row.originalFilename"
                @blur="changeStates(scope.$index)" @change="blurInput($event, scope.$index)"
                placeholder="请输入内容"></el-input>
              <span v-else>{{ scope.row.originalFilename }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="文件大小" min-width="120">
            <template v-slot="scope">
              {{ setFileSize(scope.row.size || scope.row.fileObj.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="createByName" label="上传者" />
          <el-table-column prop="createTime" label="上传时间" min-width="125">
            <template #header>
              <el-icon name="time" />
              上传时间
            </template>
          </el-table-column>
          <el-table-column prop="notes" label="备注" />
          <el-table-column label="操作" width="180" align="center" fixed="right"
            v-if="hasPermission('isPreview') || hasPermission('isRename')">
            <template v-slot="scope">
              <div class="upload-table-view-cell-btns">
                <el-button link type="primary" @click="toRefer(scope.$index, scope.row)" v-if="hasPermission('isPreview')" :disabled="!field.options.fileTypes.includes(scope.row.ext)">查看
                </el-button>
                <el-button link type="primary" @click="toDownloadFormFile(scope.row)" v-if="hasPermission('isDownload')">下载</el-button>
                <el-button link type="primary" @click="reName(scope.$index, scope.row)" v-if="hasPermission('isRename')">重命名
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>

    <template v-else-if="showFormType === 'form'">
      <div class="upload-table-view-form">
        <!-- 表单页面附件列表展示 -->
        <div v-for="(file, index) in formFlowFileList" class="file-list-img-box" :key="file.id"
          :title="file.originalFilename" @click="toClickFile(index, file)" @dblclick="toClickLookFile(file)"
          :class="{ 'clicked-div': index == clickedIndex }">
          <div style="text-align: center">
            <img v-if="file.fileExtension == 'pdf' || file.ext === 'pdf'" src="@/assets/images/uploadView/pdf.svg"
              class="file-list-img" />
            <img v-else-if="file.fileExtension == 'xls' || file.ext === 'xlsx'"
              src="@/assets/images/uploadView/excel.png" class="file-list-img" />
            <img v-else src="@/assets/images/uploadView/docx.svg" class="file-list-img" />
            <div class="file-list-name">
              {{ file.originalFilename || file.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="upload-table-view-btns">
        <div class="btns-list">
          <!-- 上传 -->
          <template v-if="hasPermission('isUpload')">
            <el-upload :multiple="field.options.multipleSelect"
              :action="field.options.uploadApi || ''" :http-request="uploadFormFile" :show-file-list="false"
              :accept="acceptType" :on-success="uploadSuccessForm" style="width: 25px"
              :before-upload="fileBeforeUpload">
              <div class="upload-table-view-btn" style="width: 25px">
                <el-icon>
                  <Upload />
                </el-icon>
              </div>
            </el-upload>
          </template>
          <!-- 删除 -->
          <div class="upload-table-view-btn" @click="toDeleteFormFile" v-if="hasPermission('isDeleted')">
            <el-icon>
              <Delete />
            </el-icon>
          </div>
          <!-- 下载 -->
          <div class="upload-table-view-btn" v-if="hasPermission('isDownload')" disabled="!isDownload"
            @click="toDownloadFormFile(null)">
            <el-icon>
              <Download />
            </el-icon>
          </div>
        </div>
      </div>
    </template>

    <template v-else-if="showFormType === 'formRow'">
      <div class="upload-table-view-form upload-table-view-formRow">
        <!-- 表单页面附件列表展示 -->
        <div v-for="(file, index) in formFlowFileList" class="file-list-img-box" :key="file.id"
          :title="file.originalFilename" @click="toClickFile(index, file)" @dblclick="toClickLookFile(file)"
          :class="{ 'clicked-div': index == clickedIndex }">
          <div style="
              text-align: center;
              display: flex;
              align-items: center;
              flex: 1;
              overflow: hidden;
            ">
            <img v-if="file.fileExtension == 'pdf' || file.ext === 'pdf'" src="@/assets/images/uploadView/pdf.svg"
              class="file-list-img" />
            <img v-else-if="file.fileExtension == 'xls' || file.ext === 'xlsx'"
              src="@/assets/images/uploadView/excel.png" class="file-list-img" />
            <img v-else src="@/assets/images/uploadView/docx.svg" class="file-list-img" />
            <div class="file-list-name">
              {{ file.originalFilename || file.name }}
            </div>
          </div>
          <div class="upload-table-view-btn" @click="toDeleteFormFile" v-if="hasPermission('isDeleted')">
            <el-icon>
              <Delete />
            </el-icon>
          </div>
          <div class="upload-table-view-btn" v-if="hasPermission('isDownload')" disabled="!isDownload"
            @click.stop="toDownloadFormFile(file)">
            <el-icon>
              <Download />
            </el-icon>
          </div>
        </div>
      </div>
      <div class="upload-table-view-btns upload-table-view-btns-formRow" v-if="hasPermission('isUpload')">
        <div class="btns-list">
          <!-- 上传 -->
          <el-upload :multiple="field.options.multipleSelect"
            :action="field.options.uploadApi || ''" :http-request="uploadFormFile" :show-file-list="false"
            :accept="acceptType" :on-success="uploadSuccessForm" style="width: 25px" :before-upload="fileBeforeUpload">
            <div class="upload-table-view-btn" style="width: 25px">
              <el-icon>
                <Upload />
              </el-icon>
            </div>
          </el-upload>
        </div>
      </div>
    </template>
    <!-- 查看部分 START -->
    <div>
      <!-- <imgPreview :imgList="imgList"></imgPreview> -->
      <Preview :visible="previewVisible" :file="activeFile" />
      <pdfPreview ref="pdfPreview" :preTitle="preTitle" :docType="docType"></pdfPreview>
    </div>
    <!-- 查看部分 END -->
  </div>
</template>

<script>
import { getEditUrl } from "@/api/upload/file";
import imgPreview from "./imgPreview.vue";
import Preview from "./Preview";
import pdfPreview from "./pdfPreview";
import {
  uploadFiles,
  deleteFile,
  renameApi,
  downloadFiles,
  downloadDocument,
  downloadDocumentZip
} from "@/api/upload/file";
import { Delete, Download, Upload } from "@element-plus/icons-vue";
import pdfImg from "@/assets/images/uploadView/pdf.svg";
import docsImg from "@/assets/images/uploadView/docx.svg";
import i18n, { translate } from "@/utils/i18n";
import Sortable from 'sortablejs';
export default {
  name: "UploadView",
  mixins: [i18n],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    field: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 流程当前状态 0等待提交 1等待审核 2审核通过 3驳回 4撤销 5作废 6挂起 7发起人作废
    status: {
      type: Number,
      default() {
        return 8;
      },
    },
    opType: { type: Number, default: 5 },
    filePermission: { type: Object, default: () => ({}) },
    isFromVform: {
      //是否来源自vform 判断是否通过filed配置判断是有权限上传等操作
      type: Boolean,
      default: true,
    },
    config: {
      //组件直接调用时的权限配置
      type: Object,
      default: () => ({
        isUpload: true,
        isDeleted: true,
        isDownload: true,
        isRename: true,
        isPreview: true,
        title: "附件列表",
      }),
    },
    processName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      docType: "",
      preTitle: "",
      previewVisible: false,
      activeFile: {},
      acceptType: "",
      imgList: [],
      rowId: "",
      listQuery: {
        currentPage: 1,
        pageSize: 20,
      },
      flowFileList: JSON.parse(JSON.stringify(this.value)),
      formFlowFileList: [],
      clickedIndex: -1,
      clickedFileInf: {},
      dataSelected: [],
      uploadLoading: false,
      uploadLength: 0,
      successUploadLength: 0,
      // el-table渲染key
      randomKey: Math.random().toString(36).valueOf(),
      // sortable配置对象
      sortable: null,
    };
  },
  components: {
    imgPreview,
    pdfPreview,
    Preview,
  },
  computed: {
    showFormType() {
      return this.field.options.showFormType;
    },
    nodeFilePermission() {
      return {
        FileNameReset: true, // 重命名
        FilePreview: true, // 预览
        FileRemove: true, // 删除
        FileUpload: true, // 上传
        FileDownload: true, // 下载
        ...this.filePermission,
      };
    },
    downloadBtnShow() {
      return this.nodeFilePermission.FileDownload;
    },
    total() {
      return this.value.length;
    },
    uploadSizeLimitTxt() {
      const { upload, fileSize, sizeUnit } = this.config;
      return upload ? `小于${fileSize}${sizeUnit}` : "";
    },
    isDownload_talble() {
      const { dataSelected } = this;
      const { length } = dataSelected;
      return length;
    },
  },
  created() { },
  mounted() {
      this.$nextTick(() => {
        // 使用closest函数查找最近的祖先元素，该元素具有指定的类名
        const parentClassName = '.el-form-item__content';
        var closestParent = this.$refs.uploadView.closest(parentClassName);
        if(closestParent){
          let styleText = (this.$refs.uploadView.closest('.el-form-item') ).getAttribute('style');
          (this.$refs.uploadView.closest('.el-form-item__content')).setAttribute('style', styleText + ';overflow:hidden;');
        }
        // this.initSortableDrop()
      })
  },  
  watch: {
    value: {
      deep: true,
      handler(val, oldVal) {
        if (
          val && val.length !== 0 &&
          JSON.stringify(val) !== JSON.stringify(oldVal)
        ) {
          let valueArr = this.value
          if (typeof val === "string") {
            valueArr = JSON.parse(val);
          }
          let _formFlowFileList = [];
          valueArr.map((item) => {
            let _item = item;
            if (typeof item === "string") {
              _item = JSON.parse(item);
            }
            _formFlowFileList.push(_item);
          });
          this.formFlowFileList = _formFlowFileList;
        }
      },
      immediate: true,
    },
    showFormType(val) { },
    formFlowFileList: {
      deep: true,
      handler(val, oldVal) {
        if (val && val.length !== 0) {
          this.flowFileList = val;
          this.formFlowFileList = val;
          this.successUploadLength = val.length;
          const url = val[0].url || "";
          this.$emit("fileChange", val);
        } else {
          this.successUploadLength = 0;
        }
      },
    },
    "field.uploadType": {
      deep: true,
      handler(val) {
        this.acceptType = "";
        if (val && val.length !== 0) {
          val.forEach((item) => {
            if (item.inputVal) {
              if (!this.acceptType) {
                this.acceptType += item.inputVal;
              } else {
                this.acceptType += `,${item.inputVal}`;
              }
            }
          });
        }
      },
    },
  },
  methods: {
    initSortableDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      // 拖拽排序
      this.sortable = Sortable.create(tbody, {
        animation: 150,
        ghostClass: 'ghost',
        filter:'.el-input__wrapper',
        preventOnFilter: false,
        onEnd: ({ newIndex, oldIndex }) => {
          this.flowFileList.splice(newIndex, 0, this.flowFileList.splice(oldIndex, 1)[0]);
          // 重置随机数，修改table的key值，触发重新渲染table组件
          this.randomKey = Math.random().toString(36).valueOf();
          this.$nextTick(() => {
            this.initSortableDrop()
            this.$emit("fileChange", this.flowFileList);
            this.$emit("update:value", this.flowFileList);
          });
        },
      });
    },
    fileBeforeUpload(file) {
      try {
        let fileTypeCheckResult = false;
        let extFileName = file.name.substring(file.name.lastIndexOf(".") + 1);
        // if (!!this.field.options && !!this.field.options.fileTypes) {
        //   let uploadFileTypes = this.field.options.fileTypes;
        //   if (uploadFileTypes.length > 0) {
        //     fileTypeCheckResult = uploadFileTypes.some((ft) => {
        //       return extFileName.toLowerCase() === ft.toLowerCase();
        //     });
        //   }
        // }
        // 除限制类型外，其他先都放开
        if (!!this.field.options && !!this.field.options.limitTypes) {
          let uploadFileTypes = this.field.options.limitTypes;
          if (uploadFileTypes.length > 0) {
            fileTypeCheckResult = !uploadFileTypes.some((ft) => {
              return extFileName.toLowerCase() === ft.toLowerCase();
            });
          }
        } else {
          let uploadFileTypes = ["jsp", "exe", "sh", "tmp"];
          if (uploadFileTypes.length > 0) {
            fileTypeCheckResult = !uploadFileTypes.some((ft) => {
              return extFileName.toLowerCase() === ft.toLowerCase();
            });
          }
        }
        if (!fileTypeCheckResult) {
          this.$message.error(
            this.i18nt("render.hint.unsupportedFileType") + extFileName
          );
          return false;
        }

        let fileSizeCheckResult = false;
        let uploadFileMaxSize = 5; //5MB
        if (!!this.field.options && !!this.field.options.fileMaxSize) {
          uploadFileMaxSize = this.field.options.fileMaxSize;
        }
        fileSizeCheckResult = file.size / 1024 / 1024 <= uploadFileMaxSize;
        if (!fileSizeCheckResult) {
          this.$message.error(
            this.i18nt("render.hint.fileSizeExceed") + uploadFileMaxSize + "MB"
          );
          return false;
        }
        this.uploadLength += 1;
        return true;
      } catch (error) {
        console.log(error);
        return false;
      }
    },
    hasPermission(name) {
      if (this.isFromVform) {
        return this.field.options[name];
      } else {
        return this.config[name];
      }
    },
    formatDateC(row) {
      let datac = row.createTime;
      let dtc = new Date(datac);
      let dtuMonth = dtc.getMonth() + 1;
      //获取日
      let dtuDay = dtc.getDate();
      //处理1-9月前面加0
      if (dtuMonth < 10) {
        dtuMonth = "0" + (dtc.getMonth() + 1);
      }
      //处理1-9天前面加0
      if (dtuDay < 10) {
        dtuDay = "0" + dtc.getDate();
      }
      //获取小时
      let dtuHours = dtc.getHours();
      //处理1-9时前面加0
      if (dtuHours < 10) {
        dtuHours = "0" + dtc.getHours();
      }
      //获取分钟
      let dtuMinutes = dtc.getMinutes();
      //处理1-9分前面加0
      if (dtuMinutes < 10) {
        dtuMinutes = "0" + dtc.getMinutes();
      }
      //获取秒
      let dtuSeconds = dtc.getSeconds();
      //处理1-9秒前面加0
      if (dtuSeconds < 10) {
        dtuSeconds = "0" + dtc.getSeconds();
      }
      //组装年月日时分秒,按自己的要求来
      return dtc.getFullYear() + "/" + dtuMonth + "/" + dtuDay;
      //+ " " + dtuHours + ":" + dtuMinutes + ":" + dtuSeconds
    },
    initPageData(data) {
      this.listQuery.currentPage = data.page;
      this.listQuery.pageSize = data.limit;
      this.$emit("initPageData", data);
    },
    validDate(DATE) {
      let year = DATE.getFullYear(),
        month = DATE.getMonth() >= 10 ? DATE.getMonth() : `0${DATE.getMonth()}`,
        date = DATE.getDate() >= 10 ? DATE.getDate() : `0${DATE.getDate()}`,
        hours = DATE.getHours() >= 10 ? DATE.getHours() : `0${DATE.getHours()}`,
        minutes =
          DATE.getMinutes() >= 10 ? DATE.getMinutes() : `0${DATE.getMinutes()}`;
      return `${year}-${month}-${date} ${hours}:${minutes}`;
    },
    // 处理文件大小
    setFileSize(sizeNum) {
      const fileSize =
        Math.ceil(sizeNum / 1024) < 1024
          ? `${Math.ceil(sizeNum / 1024)}KB`
          : `${Math.ceil(sizeNum / 1024 / 1024)}M`;
      return fileSize;
    },
    // 自定义上传文件
    uploadFile(obj) {
      if (this.successUploadLength >= this.field.options.limit) {
        this.$message.error('上传文件数量已超出允许上限');
        this.uploadLength = 0;
        return false;
      }
      let fileSize = obj.file.size;
      const formData = new FormData();
      formData.append("file", obj.file);
      let fileObj = {
        size: fileSize,
      };
      let uploadType = this.showFormType !== "flow" ? "flow" : "referTo";
      this.uploadLoading = true
      uploadFiles(formData).then((res) => {
        let { ok, data } = res;
        if (ok == true) {
          fileObj.uploadtime = this.validDate(new Date(data.createTime));
          fileObj.name = data.filename;
          fileObj.fileExtension = data.ext;
          fileObj.createByName = data.createByName;
          fileObj.url = data.url;
          let newFileObj = {
            uploadTypes: "nosave",
            showInput: false,
            ...data,
            ...fileObj,
          };
          this.flowFileList.push(newFileObj);
          setTimeout(() => {
            this.$emit("fileChange", this.flowFileList, {type: "uploadSuccess"});
            this.$emit("update:value", this.flowFileList);
          }, 0);
        } else {
          this.uploadLoading = false
        }
        this.uploadLength -= 1;
        if (this.uploadLength == 0) {
          this.uploadLoading = false
        }
      }).catch(err => {
        this.uploadLoading = false
      })
    },
    uploadFormFile(obj) {
      if (this.successUploadLength >= this.field.options.limit) {
        this.$message.error('已超出允许上传文件数量上限');
        this.uploadLength = 0;
        return false;
      }
      let fileSize = obj.file.size;
      const formData = new FormData();
      formData.append("file", obj.file);
      let fileObj = {
        size: fileSize,
      };
      let uploadType = this.showFormType !== "table" ? "flow" : "referTo";
      this.uploadLoading = true
      uploadFiles(formData).then((res) => {
        let { ok, data } = res;
        if (ok == true) {
          fileObj.uploadtime = this.validDate(new Date(data.createTime));
          fileObj.name = data.filename;
          fileObj.fileExtension = data.ext;
          fileObj.createByName = data.createByName;
          fileObj.url = data.url;
          if (
            fileObj.fileExtension == "docx" ||
            fileObj.fileExtension == "pdf"
          ) {
            var fileImg = pdfImg;
          } else {
            var fileImg = docsImg;
          }
          fileObj.fileImg = fileImg;
          let newFileObj = {
            uploadTypes: "nosave",
            showInput: false,
            ...data,
            ...fileObj,
          };
          this.formFlowFileList.push(newFileObj);
          setTimeout(() => {
            this.$emit("fileChange", this.flowFileList);
            this.$emit("update:value", this.flowFileList);
          }, 0);
        } else {
          this.uploadLoading = false
        }
        this.uploadLength -= 1;
        if (this.uploadLength == 0) {
          this.uploadLoading = false
        }
      }).catch(er => {
        this.uploadLoading = false
      })
    },
    selectedChange(val) {
      this.dataSelected = val;
    },
    uploadSuccess(res, file, fileList) {
      console.log(res, file, formFlowFileList);
    },
    uploadSuccessForm(res, file, formFlowFileList) {
      console.log(res, file, formFlowFileList);
    },
    toRefer(index, row) {
      this.preTitle = row.originalFilename;
      this.$refs.pdfPreview.getFilsUrl(row.id);
    },
    toDelete(index, row) {
      if (row && !row.uploadTypes) {
        let param = {
          fileDetailIds: [row.id],
        };
        deleteFile(param).then((res) => {
          if (res.code == 0) {
          }
        });
      }
      this.flowFileList.splice(index, 1);
      this.$emit("fileChange", this.flowFileList);
      this.$emit("update:value", this.flowFileList);
    },
    // 点击图标更新当前信息
    toClickFile(index, file) {
      this.clickedIndex = index;
      this.clickedFileInf = file;
    },
    toClickLookFile(file) {
      this.toRefer(1, file)
    },
    toDeleteFormFile() {
      // 公文拟文表单风格删除功能
      if ((this.clickedIndex == -1 || this.clickedFileInf == {})) {
        this.$message({
          message: "请选择要删除的文件",
          type: "error",
        });
        return;
      }
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const index = this.clickedIndex;
          // const row = this.formFlowFileList[index];
          // if (row && !row.uploadTypes) {
          //   let param = {
          //     fileDetailIds: [row.id],
          //   };
          //   deleteFile(param).then((res) => {
          //     if (res.code == 0) {
          //     }
          //   });
          // }
          this.formFlowFileList.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.clickedIndex = -1;
          this.clickedFileInf = {};
          this.$emit("fileChange", this.flowFileList);
          this.$emit("update:value", this.flowFileList);
        })
        .catch(() => {
        });
    },
    changeStates(index) {
      this.flowFileList[index].showInput = false;
    },
    blurInput(value, index) {
      let obj = {
        name: value,
        id: this.rowId,
      };
      renameApi(obj).then((res) => {
        let { code } = res;
        if (code == 0) {
          this.flowFileList[index].showInput = false;
          this.flowFileList[index].fileName = value;
          this.$emit("fileChange", this.flowFileList);
          this.$emit("update:value", this.flowFileList);
        }
      });
      this.showInput = false;
    },
    reName(index, row) {
      this.flowFileList[index].showInput = true;
      this.rowId = row.id;
    },
    allDelete() {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let fileDetailIds = [];
          this.dataSelected.forEach((item) => {
            fileDetailIds.push(item.id);
            let index = this.flowFileList.findIndex((old) => {
              return item.id == old.id;
            });
            this.flowFileList.splice(index, 1);
          });
          // deleteFile({ fileDetailIds }).then((res) => {
          //   if (res.code == 0) {
          //   }
          // });
          this.$emit("fileChange", this.flowFileList);
          this.$emit("update:value", this.flowFileList);
        })
        .catch(() => { });
    },
    toDownloads() {
      // const handleDownload = (item) => {
      //   const { id, originalFilename } = item;

      //   downloadDocument(id, originalFilename)

      // };
      
      // this.dataSelected.forEach(handleDownload);

      let obj= {
        zipName: this.processName,
        zipInfo:[]
      }
      this.dataSelected.forEach(item=>{
        obj.zipInfo.push({
          fileId:item.id,
          fileName:item.originalFilename
        })
      })
      downloadDocumentZip(obj)
    },

    toDownloadFormFile(file) {
      // 公文拟文表单风格下载功能
      const down = ({ id, originalFilename, ext }) => {
        downloadDocument(id, originalFilename)
      };
      if (!file && (this.clickedIndex == -1 || this.clickedFileInf == {})) {
        this.$message({
          message: "请选择要下载的文件",
          type: "error",
        });
      } else {
        down(file || this.clickedFileInf);
      }
    },

    /**
     * 接收上传文件审查后的文件列表
     * @param fileList * @description 文件列表
     */
    uploadFileList(fileList) {
      console.log(fileList);
      if (fileList && fileList.length) {
        fileList.forEach((data) => {
          if (data) {
            let fileObj = {
              size: data.size,
            };
            fileObj.uploadtime = this.validDate(new Date(data.createTime));
            fileObj.name = data.filename;
            fileObj.fileExtension = data.ext;
            fileObj.createByName = data.createByName;
            fileObj.url = data.url;
            if (
              fileObj.fileExtension == "docx" ||
              fileObj.fileExtension == "pdf"
            ) {
              var fileImg = pdfImg;
            } else {
              var fileImg = docsImg;
            }
            fileObj.fileImg = fileImg;
            let newFileObj = {
              uploadTypes: "nosave",
              showInput: false,
              ...data,
              ...fileObj,
            };
            this.flowFileList.push(newFileObj);
            this.$emit("fileChange", this.flowFileList);
            this.$emit("update:value", this.flowFileList);
          } else {
            this.uploadLoading = false
          }
          this.uploadLength -= 1;
          if (this.uploadLength == 0) {
            this.uploadLoading = false
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  width: 100%;
}

.upload-table-view {
  position: relative;
  padding: 10px;
  background-color: #fff;
  z-index: 8;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  box-sizing: border-box;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .upload-table-view-title {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    line-height: 24px;
    padding-bottom: 10px;
    box-sizing: border-box;

    .upload-table-view-title-icon {
      margin-right: 10px;
      color: #999;
    }

    .upload-table-view-title-text {
      color: #999;
      font-weight: 700;
    }
  }

  .upload-table-view-table {
    flex-grow: 1;
    overflow: hidden;

    >.el-table__body-wrapper.is-scrolling-none {
      height: 100% !important;
    }
  }

  .upload-table-view-btns {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    padding: 0px;
  }
}

.log-content {
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #e5e5e5;
}

// 流程表单中的附件框样式
.log-content.form {
  position: relative;
  background-color: #fff;
  z-index: 8;
  height: 100%;
  min-height: 80px;

  &>.upload-table-view-form {
    width: calc(100% - 100px);
    height: 100%;

    .file-list-img-box {
      border-radius: 3px;
      padding: 5px 0;
      width: 70px;
      float: left;
      cursor: pointer;

      &:hover {
        background: #eaf0f5;
      }

      .file-list-img {
        height: 35px;
        width: 35px;
      }

      .file-list-name {
        // font-size: 12px;
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        text-align: center;
      }
    }

    .clicked-div {
      background: #d7e1e8 !important;
    }
  }

  &>.upload-table-view-formRow {
    width: calc(100% - 50px);
    display: flex;
    flex-direction: column;

    .file-list-img-box {
      width: 100%;
      line-height: 26px;
      display: flex;
      padding: 0;
      overflow: hidden;

      .file-list-img {
        height: 15px;
        width: 15px;
        margin: 0 6px;
      }

      .file-list-name {
        // font-size: 12px;
        padding-right: 10px;
        flex: 1;
        text-align: left;
      }

      .upload-table-view-btn {
        padding-right: 6px;
      }
    }
  }

  &>.upload-table-view-btns {
    // position: absolute;
    // top: 15px;
    // right: 15px;
    max-width: 75px;
    height: 25px;
    // width: 100px;
    background: #f7f7f7;

    .btns-list {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      line-height: 25px;
      border-radius: 3px;
      border: 1px solid #e3e3e3;

      .upload-table-view-btn {
        height: 25px;
        width: 25px;
        background: none;
        border: 0;
        text-align: center;

        &:hover {
          cursor: pointer;
          background: #e3e3e3;
          border: 0;
          height: 25px;
          width: 25px;
        }
      }
    }
  }

  .upload-table-view-btns-formRow {
    width: 25px;
    max-width: 25px;
  }
}

.form.flex {
  justify-content: space-between;
}

.flex {
  display: flex;
}
</style>